import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, getRole, setRole, removeRole } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    role: getRole()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROLE: (state, role) => {
    state.role = role
    setRole(role)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_ROLE', data.role)
        // 直接保存登录时输入的用户名
        commit('SET_NAME', username.trim())
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve) => {
      // 直接使用已保存的用户名，不需要调用接口
      const userName = state.name || 'user'
      const userRole = state.role
      commit('SET_NAME', userName)
      commit('SET_AVATAR', '')
      // 根据role字段设置角色权限
      if (userRole === '0' || userRole === 0) {
        commit('SET_ROLES', ['admin'])
      } else {
        commit('SET_ROLES', ['user'])
      }
      resolve({ name: userName, role: userRole })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeRole() // remove role storage
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeRole() // remove role storage
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

